package com.example.day19;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    TextView text1;
    Button bendi;
    SeekBar progress;

    boolean isAccess=false;//授权

    ListView music_list;//播放列表
    List<musicData> datalist = null;
    musicAdapter adapter;
    musicData nowMusic;
//    MediaPlayer mp;
    Button play, stop, next, last;
    MyMusicService.MyBinder binder;
    //绑定服务连接
    ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (MyMusicService.MyBinder)service;
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        register();
        text1 = findViewById(R.id.name);
        music_list = findViewById(R.id.list1);
        progress = findViewById(R.id.progress);
        play = findViewById(R.id.play);
        stop = findViewById(R.id.stop);
        next = findViewById(R.id.next);
        last = findViewById(R.id.last);
        play.setOnClickListener(this);
        stop.setOnClickListener(this);
        next.setOnClickListener(this);
        last.setOnClickListener(this);
        bendi = findViewById(R.id.bendi);
        isAccess=  new ActivityTools().checkAccess("android.permission.WRITE_EXTERNAL_STORAGE", 1,MainActivity.this);

        Intent intent =new Intent(this,MyMusicService.class);
        //参数一：intent意图  参数二：绑定服务连接  参数三：flag标记BIND_AUTO_CREATE 绑定的时候自动创建服务
        startService(intent);
        bindService(intent,connection, Service.BIND_AUTO_CREATE);

        bendi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isAccess){
                    music();
                }else{
                    Toast.makeText(MainActivity.this,"未获得文件读取权限",Toast.LENGTH_SHORT).show();
                }
          }
        });
        music_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                nowMusic=datalist.get(position);
                binder.stopMusic();
                binder.initPlayer(nowMusic);
            }
        });
        progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int aa=0;
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Log.i("######","onProgressChanged=" +progress);
                aa=progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Log.i("######","onStartTrackingTouch=");
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Log.i("######","onStopTrackingTouch=");
//                playTime=aa;
//                mp.seekTo(playTime);
            }
        });
    }

    /**
     * 获得授权返回
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        android.permission.WRITE_EXTERNAL_STORAGE
        if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // TODO: 2019/6/15 获得授权执行操作
//http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1
            isAccess=true;
        } else {
            // TODO: 2019/6/15 未获得授权执行的操作
            finish();
        }
    }

    /**
     * 注册
     */
    public void register(){
        Log.e("@@@@@@@@@@@@@","onStartCommand");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("start");
        intentFilter.addAction("stop");
        intentFilter.addAction("last");
        intentFilter.addAction("next");
        ButtonBroadcastReceiver myReciver = new ButtonBroadcastReceiver();
        registerReceiver(myReciver,intentFilter);
    }

    public void music() {
        //TODO 1:获得ContentResolver
        ContentResolver contentResolver = getContentResolver();
        //参数一 URI   null
        //TODO 2:获得音频的URI
        Uri uri1 = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;//音频的URI
        Log.e("PERMISION_CODE", uri1.getPath() + "***");
        Cursor cursor = contentResolver.query(uri1, null, null, null, null);
        Log.e("111######", cursor.getCount() + "没有音乐！！！");
        if (cursor == null || cursor.getCount() <= 0) {
            Log.e("######", "没有音乐！！！");
            return;
        }
        datalist = new ArrayList<>();
        int a = 0;
        while (cursor.moveToNext()) {
            //字段
            musicData mdata = new musicData();
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));

            mdata.setTitle(title);
            mdata.setArtist(artist);
            mdata.setData(data);
            mdata.setDuration(duration);
            mdata.setSize(size);
            mdata.setSort(a);
            a++;
            datalist.add(mdata);

            Log.e("###", "音乐: " + title + ":" + data + ":" + artist + ":" + duration + ":" + size);
        }
        adapter = new musicAdapter(MainActivity.this, datalist);
        music_list.setAdapter(adapter);
        nowMusic = datalist.get(0);

        if(binder.initPlayer(nowMusic)){
            // TODO: 2019/6/28  当加载完成显示当前加载的曲目
            int totalTime = Math.round(nowMusic.duration / 1000);
            String str = String.format("%02d:%02d", totalTime / 60,
                    totalTime % 60);
            text1.setText(nowMusic.getTitle()+str);
            progress.setMax((int)nowMusic.getDuration());
//            发送通知
            sendNotification();
        }
//        binder.initPlayer(nowMusic);
    }
    @TargetApi(Build.VERSION_CODES.N)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void  sendNotification(){
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentTitle("自定义通知");

        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.noti_layout);
        String aaa=nowMusic.getTitle();
        Log.e("######",aaa+"llllllll");
        remoteViews.setTextViewText(R.id.text1, aaa);

        Intent intent1 = new Intent();
        intent1.setAction("last");
/*
　pendingIntent对象,使用方法类的静态方法 :
　　　  getActivity(Context, int, Intent, int)------->跳转到一个activity组件、
　　　　getBroadcast(Context, int, Intent, int)------>打开一个广播组件
　　　　getService(Context, int, Intent, int)-------->打开一个服务组件。
 */
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 101, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.b1, pendingIntent);

        Intent intent2 = new Intent();
        intent2.setAction("start");
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 101, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.b2, pendingIntent1);

        Intent intent3 = new Intent();
        intent3.setAction("stop");
        PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 101, intent3, PendingIntent.FLAG_CANCEL_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.b3, pendingIntent2);

        Intent intent4 = new Intent();
        intent4.setAction("next");
        PendingIntent pendingIntent3 = PendingIntent.getBroadcast(this, 101, intent4, PendingIntent.FLAG_CANCEL_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.b4, pendingIntent3);

        builder.setContent(remoteViews);

        manager.notify(1000, builder.build());
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play:
                binder.playMusic();
                break;
            case R.id.stop:
                binder.stopMusic();
                break;
            case R.id.last:
                int num = nowMusic.getSort();
                if (num == 0) {
                    num = datalist.size() - 1;
                } else {
                    num = num - 1;
                }
                nowMusic = datalist.get(num);
                binder.next(nowMusic);
                break;
            case R.id.next:
                int num2 = nowMusic.getSort();
                if (num2 == datalist.size() - 1) {
                    num2 = 0;
                } else {
                    num2 = num2 + 1;
                }
                nowMusic = datalist.get(num2);
                binder.next(nowMusic);
                break;
            default:
                break;
        }

    }

    /**
     * 广播监听
     */
    public class ButtonBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e("######","播"+action+"放");
            if (action.equals("start")) {
                //通过传递过来的ID判断按钮点击属性或者通过getResultCode()获得相应点击事件
                binder.playMusic();
            }else if (action.equals("stop")){
                binder.stopMusic();
            }else if (action.equals("next")){
                int num2 = nowMusic.getSort();
                if (num2 == datalist.size() - 1) {
                    num2 = 0;
                } else {
                    num2 = num2 + 1;
                }
                nowMusic = datalist.get(num2);
                binder.next(nowMusic);
            }else if (action.equals("last")){
                int num = nowMusic.getSort();
                if (num == 0) {
                    num = datalist.size() - 1;
                } else {
                    num = num - 1;
                }
                nowMusic = datalist.get(num);
                binder.next(nowMusic);
            }
            int totalTime = Math.round(nowMusic.duration / 1000);
            String str = String.format("%02d:%02d", totalTime / 60,
                    totalTime % 60);
            text1.setText(nowMusic.getTitle()+str);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
